//
//  MKOAuthViewController.swift
//  Weibo
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 MK. All rights reserved.
//

/*
获取access_token
*/


import UIKit
import SVProgressHUD
import AFNetworking

class MKOAuthViewController: UIViewController {
    
    let web = UIWebView()
    override func loadView() {
        view = web
        web.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBar()
        requestOAuth()
        
    }
    
    
    
}


private extension MKOAuthViewController {
    
    //设置导航条
    func setNavigationBar() {
        title = "授权登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "backMoudluePage")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "saveUserSinaData")
    }
    
    @objc func backMoudluePage() {
       self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func saveUserSinaData() {
        let jsonStr = "document.getElementById('userId').value = '1006980087@qq.com' ,document.getElementById('passwd').value = 'xu123456'"
        web.stringByEvaluatingJavaScriptFromString(jsonStr)
    }
    
    //OAuth授权请求
    func requestOAuth() {
        
        //webView请求页面 用.loadRequest()就OK了
        let str = "https://api.weibo.com/oauth2/authorize?"
        let url = NSURL(string: str + "client_id=" + client_id + "&redirect_uri=" + redirect_uri)
        let request = NSURLRequest(URL: url!)
        web.loadRequest(request)
        
    }
    
}

//webView遵守协议 实现代理方法 - 解决加载延迟时 显示空白页面
extension MKOAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("加载中,请稍候", maskType: .None)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //从js交互中能获取到请求的URLString -(应该开始加载的请求)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print(request.URL)
        
        //从URL中获取字符串
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //只要前缀中包含 则执行此请求
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        //只要是前缀中不包含 则此请求不执行
        if !urlString.hasPrefix("http://www.baidu.com") {
            return false
        }
        
        //FIXME: - query能获取URL的参数部分: code=c7319b02402f8c82ddb469b758a70eeb
        let query = request.URL?.query
        if let queryStr = query {
            let str = "code="
            let code = queryStr.substringFromIndex(str.endIndex)
            //获取用户的令牌
            gotToken(code)
        }
        
        return true
    }
    
    //获取用户的令牌
    func gotToken(code: String) {
        //获取用户的令牌
        MKUserInfoViewModer().loadAccess_token(code) { (isSuccess) -> () in
            if isSuccess {
                print("登录成功")
                
                //如果登录成功 就跳转到首页
                //self.backMoudluePage()
                self.dismissViewControllerAnimated(true) { () -> Void in
                    //FIXME: -利用通知 更改根控制器跳转到到首页
                    NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: "goWelcome")
                }
                
                
            } else {
                print("登录失败")
            }
        }
        
    }
    
}